package com.webware.view.client;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.History;
import com.webware.view.client.event.ChangeSearchStringEvent;
import com.webware.view.client.event.ChangeSearchStringEventHandler;
import com.webware.view.client.event.DoSearchEvent;
import com.webware.view.client.event.DoSearchEventHandler;
import com.webware.view.client.presenter.Presenter;

public class AppController implements Presenter, ValueChangeHandler<String> {
    private final ClientFactory clientFacory;

    public AppController(ClientFactory clientFactory) {
	this.clientFacory = clientFactory;
	bind();
    }

    private void bind() {
	History.addValueChangeHandler(this);

	clientFacory.getEventBus().addHandler(ChangeSearchStringEvent.TYPE,
		new ChangeSearchStringEventHandler() {
		    public void onChange(ChangeSearchStringEvent event) {
			doChangeSearchBox();
		    }
		});
	clientFacory.getEventBus().addHandler(DoSearchEvent.TYPE,
		new DoSearchEventHandler() {
		    public void onSearch(DoSearchEvent event) {
			doSearch();
		    }
		});
    }

    protected void doChangeSearchBox() {
	System.out.println("doChangeSearchBox");
    }

    private void doSearch() {
	System.out.println("doSearch");
	History.newItem("search");
    }

    public void onValueChange(ValueChangeEvent<String> event) {
	String token = event.getValue();

	if (token != null) {
	    // Presenter presenter = null;
	    //
	    // if (token.equals("search")) {
	    // presenter = new HeaderPresenter();
	    // }
	    //
	    // if (presenter != null) {
	    // presenter.goTo(container);
	    // }
	}
    }

    public void goTo(Place place) {
	History.fireCurrentHistoryState();
    }
}
